Module modInterco

    Private isError As Boolean
    Private dtBP As DataTable
    Private dtcsCnt As DataTable
    Private dtPURHDr As DataTable
    Private dtAPCNHDr As DataTable
    Private dtItem As DataTable
    Private dtAC As DataTable

    ' Company Default Structure
    Private InputFolderPath As String = p_oCompDef.sInboxDir

    Public Function UploadINTERCO(ByVal sSubFolder As String, ByRef sErrdesc As String) As Long

        'Event      :   UploadINTERCO()
        'Purpose    :   For Checking Errors & updation of data in SAP from AR INTERCO CSV Files
        'Author     :   Sri
        'Date       :   20 Nov 2013   

        Dim sFuncName As String = String.Empty
        Dim IsFileExist As Boolean
        Dim sFileType As String = String.Empty
        Dim oDvHdr As DataView = Nothing
        Dim oDvDtl As DataView = Nothing
        Dim sFileName As String = String.Empty

        Try
            sFuncName = "UploadINTERCO()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            Dim DirInfo As New System.IO.DirectoryInfo(p_oCompDef.sInboxDir & "\" & sSubFolder)
            Dim files() As System.IO.FileInfo

            files = DirInfo.GetFiles("*IC*.csv")

            For Each File As System.IO.FileInfo In files
                IsFileExist = True
                sFileType = Replace(File.Name, ".csv", "").Trim
                If Right(sFileType, 3) = "Dtl" Then
                    oDvDtl = GetDataViewFromCSV(File.FullName)
                Else
                    oDvHdr = GetDataViewFromCSV(File.FullName)
                    sFileName = File.Name
                    If p_iDebugMode = DEBUG_ON Then WriteToLogFile_Debug("Calling readCSVFileAR_Header for " & File.FullName & " to check error in CSV file", sFuncName)
                    readCSVFileAR_Header(File.FullName, oDvHdr)
                    If isError = True Then
                        sErrdesc = "Wrong data in CSV file " & File.FullName & ".Please refer to error log for more details"
                        If p_iDebugMode = DEBUG_ON Then WriteToLogFile_Debug(sErrdesc, sFuncName)
                        WriteToLogFile(sErrdesc, sFuncName)
                        AddDataToTable(p_oDtError, File.Name, "Error", sErrdesc)
                    End If
                End If
            Next

            If isError = True Then
                For Each file As System.IO.FileInfo In files
                    FileMoveToArchive(file, file.FullName, RTN_ERROR)
                Next
                Throw New ArgumentException(sErrdesc)
            End If

            If IsFileExist = False Then
                If p_iDebugMode = DEBUG_ON Then WriteToLogFile_Debug("No INTERCO CSV available for updation", sFuncName)
            Else
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Function ProcessARINTERCOFile()", sFuncName)
                If ProcessARINTERCOFile(oDvHdr, oDvDtl, sFileName, sErrdesc) <> RTN_SUCCESS Then
                    For Each file As System.IO.FileInfo In files
                        AddDataToTable(p_oDtError, file.Name, "Error", sErrdesc)
                        FileMoveToArchive(file, file.FullName, RTN_ERROR)
                    Next
                    Throw New ArgumentException(sErrdesc)
                Else
                    'Mvoe files
                    For Each file As System.IO.FileInfo In files
                        FileMoveToArchive(file, file.FullName, RTN_SUCCESS)
                    Next
                End If
            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Function Completed Successfully.", sFuncName)

            UploadINTERCO = RTN_SUCCESS

        Catch ex As Exception
            UploadINTERCO = RTN_ERROR
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error in Uplodiang AR file.", sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Function

    Private Sub readCSVFileAR_Header(ByVal CurrFileToUpload As String, ByVal dv As DataView)

        'Event      :   readCSVFileAR_Header
        'Purpose    :   For reading of Business Partner CSV file
        'Author     :   Sri 
        'Date       :   24 NOV 2013 

        Dim sFuncName As String = "readCSVFileAR_Header"
        Dim sSQL As String = String.Empty
        Dim dt As DataTable

        Try

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function...", sFuncName)
            sSQL = "SELECT ""Code"" FROM ""@AI_TB01_COMPANYDATA"""
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
            dt = ExecuteSQLQueryForDT(sSQL)

            For i As Integer = 0 To dv.Count - 1
                With oARHeaderDef
                    .OwnerEntityCode = dv(i)(0).ToString
                    .DocumentType = dv(i)(1).ToString
                    .DocumentNo = dv(i)(2).ToString
                    .DocumentDate = dv(i)(3)
                    .CustomerCode = dv(i)(4).ToString
                    .ReferenceNumber = dv(i)(5).ToString
                    .ChitNo = dv(i)(6).ToString
                    .ClinicCode = dv(i)(7).ToString
                    .Description = dv(i)(8).ToString
                    .TaxCode = dv(i)(9).ToString
                    .PreTaxAmount = dv(i)(10)
                    .TaxAmount = dv(i)(11)
                    .TotalAmount = dv(i)(12)
                    .CurrencyCode = dv(i)(13).ToString
                    .ExchangeRate = dv(i)(14)
                    .PaymentMethod = dv(i)(15).ToString
                    .PaymentReceived = dv(i)(16)
                    .ImportToAP = dv(i)(17).ToString
                    .SupplierCode = dv(i)(18).ToString

                    If .OwnerEntityCode.Length = 0 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". OwnerEntityCode is mandatory", sFuncName)
                    End If

                    dt.DefaultView.RowFilter = "Code = '" & dv(i)(0).ToString & "'"
                    If dt.DefaultView.Count = 0 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & ". Owner enttiy code ::" & dv(i)(0).ToString & " does not exist in SAP [@AI_TB01_COMPANYDATA] table.", sFuncName)
                    End If

                    If .DocumentType.Length > 3 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Document Type Length is not greater then 3", sFuncName)
                    End If

                    If .DocumentNo.Length > 30 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Document No Length is not greater then 30", sFuncName)
                    End If


                    If .CustomerCode.Length > 10 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Customer Code Length is not greater then 10", sFuncName)
                    End If

                    If .ReferenceNumber.Length > 30 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Reference Number Length is not greater then 80", sFuncName)
                    End If
                    If .ChitNo.Length > 40 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". ChitNo Length is not greater then 40", sFuncName)
                    End If

                    If .ClinicCode.Length > 10 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". ClinicCode Length is not greater then 10", sFuncName)
                    End If


                    If .Description.Length > 255 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Country Length is not greater then 255", sFuncName)
                    End If
                    If .TaxCode.Length > 6 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". TaxCode Length is not greater then 3", sFuncName)
                    End If

                    If .CurrencyCode.Length > 3 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Currency Code Length is not greater then 3", sFuncName)
                    End If

                    If .PaymentMethod.Length > 50 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". PaymentMethod Length is not greater then 100", sFuncName)
                    End If

                End With
            Next


        Catch ex As Exception
            isError = True
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error occured while reading content of  " & ex.Message, sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Sub

    Private Sub readCSVFileAR_Details(ByVal CurrFileToUpload As String, ByVal dv As DataView)

        'Event      :   readCSVFileAR_Details
        'Purpose    :   For reading of AR Dtl CSV file
        'Author     :   Sri 
        'Date       :   24 NOV 2013 

        Dim sFuncName As String = "readCSVFileAR_Details"
        Dim sSQL As String = String.Empty
        Dim dtItem As DataTable

        Try

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function..", sFuncName)
            sSQL = "Select ""ItemCode"" From OITM"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
            dtItem = ExecuteSQLQueryForDT(sSQL)



            For i As Integer = 0 To dv.Count - 1
                With oARHeaderDef
                    .OwnerEntityCode = dv(i)(0).ToString
                    .DocumentType = dv(i)(1).ToString
                    .DocumentNo = dv(i)(2).ToString
                    .DocumentDate = dv(i)(3)
                    .CustomerCode = dv(i)(4).ToString
                    .ReferenceNumber = dv(i)(5).ToString
                    .ChitNo = dv(i)(6).ToString
                    .ClinicCode = dv(i)(7).ToString
                    .Description = dv(i)(8).ToString
                    .TaxCode = dv(i)(9).ToString
                    .PreTaxAmount = dv(i)(10)
                    .TaxAmount = dv(i)(11)
                    .TotalAmount = dv(i)(12)
                    .CurrencyCode = dv(i)(13).ToString
                    .ExchangeRate = dv(i)(14)
                    .PaymentMethod = dv(i)(15).ToString
                    .PaymentReceived = dv(i)(16)
                    .ImportToAP = dv(i)(17).ToString
                    .SupplierCode = dv(i)(18).ToString

                    If .OwnerEntityCode.Length = 0 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". OwnerEntityCode is mandatory", sFuncName)
                    End If
                    If .DocumentType.Length > 3 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Document Type Length is not greater then 3", sFuncName)
                    End If
                    If .DocumentNo.Length > 30 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Document No Length is not greater then 30", sFuncName)
                    End If

                    If .CustomerCode.Length > 10 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Customer Code Length is not greater then 10", sFuncName)
                    End If


                    If .ReferenceNumber.Length > 30 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Reference Number Length is not greater then 80", sFuncName)
                    End If
                    If .ChitNo.Length > 40 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". ChitNo Length is not greater then 40", sFuncName)
                    End If
                    If .ClinicCode.Length > 10 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". ClinicCode Length is not greater then 10", sFuncName)
                    End If
                    If .Description.Length > 255 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Country Length is not greater then 255", sFuncName)
                    End If
                    If .TaxCode.Length > 3 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". TaxCode Length is not greater then 3", sFuncName)
                    End If

                    If .CurrencyCode.Length > 3 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". Currency Code Length is not greater then 3", sFuncName)
                    End If

                    If .PaymentMethod.Length > 50 Then
                        isError = True
                        Call WriteToLogFile("Check line no : " & CStr(i + 1) & " in " & CurrFileToUpload & ". PaymentMethod Length is not greater then 100", sFuncName)
                    End If

                End With
            Next


        Catch ex As Exception
            isError = True
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error occured while reading content of  " & ex.Message, sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Sub

    Private Function ProcessARINTERCOFile(ByVal oDvHdr As DataView, _
                                   ByVal oDvDtl As DataView, _
                                   ByVal sFileName As String, _
                                   ByRef sErrdesc As String) As Long

        Dim sFuncName As String = "ProcessARINTERCOFile"
        Dim oDtHdr As New DataTable
        Dim oDIComp() As SAPbobsCOM.Company = Nothing
        Dim oDt As DataTable
        Dim oCompanyAP As SAPbobsCOM.Company = Nothing
        Dim sSupplierCode As String = String.Empty
        Dim sSQL As String = String.Empty

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("getting distinct DBs in the file.", sFuncName)
            'For Interco Customer code will be the DB

            oDt = oDvHdr.Table.DefaultView.ToTable(True, "F5")
            Dim oEntity As New ArrayList

            For Each dr As DataRow In oDt.Rows
                Dim k As Integer
                Dim sCode As String = dr.Item(0).ToString
                k = InStr(sCode, "-")
                If k <> 0 Then sCode = Microsoft.VisualBasic.Left(sCode, k - 1).Trim
                sCode = Right(sCode, sCode.Length - 2)
                If Not oEntity.Contains(sCode) Then
                    oEntity.Add(sCode)
                End If
            Next

            ReDim oDIComp(oEntity.Count)

            For j As Integer = 0 To oEntity.Count - 1

                oDIComp(j) = New SAPbobsCOM.Company

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling ConnectToTargetCompany()", sFuncName)
                If ConnectToTargetCompany(oDIComp(j), oEntity(j).ToString, sErrdesc) <> RTN_SUCCESS Then
                    Throw New ArgumentException(sErrdesc)
                End If

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting transaction on company database " & oDIComp(j).CompanyDB, sFuncName)
                oDIComp(j).StartTransaction()

                'Dim DBRows() As DataRow = oDvHdr.Table.Select("F5='" & oDt.Rows(j).Item(0).ToString & "'")

                Dim oDVH As DataTable
                oDVH = oDvHdr.ToTable.Clone
                oDVH.Clear()

                For Each DtRow As DataRow In oDvHdr.Table.Rows
                    Dim k As Integer
                    Dim sCode As String = DtRow.Item(4).ToString
                    k = InStr(sCode, "-")
                    If k <> 0 Then sCode = Microsoft.VisualBasic.Left(sCode, k - 1).Trim
                    sCode = Right(sCode, sCode.Length - 2)
                    If sCode = oEntity(j).ToString Then
                        oDVH.ImportRow(DtRow)
                    End If
                Next

                For Each row As DataRow In oDVH.Rows

                    sSQL = "Select ""CardCode"" From OCRD WHERE ""CardType"" = 'S'"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtBP = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    sSQL = "select ""PrcCode"" from OPRC"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtcsCnt = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Opening a datatable for Invoice Ref.Doc NO.", sFuncName)
                    sSQL = "SELECT ""U_AI_RefDocNum"" FROM OPCH WHERE ""U_AI_RefDocNum"" IS NOT NULL"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtPURHDr = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    'CALL CREATE AP INVOICE
                    sSupplierCode = row.Item(18).ToString
                    If sSupplierCode = String.Empty Then
                        sErrdesc = "No supplier code found for Document N0:::" & row(2).ToString
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug(sErrdesc, sFuncName)
                        Throw New ArgumentException(sErrdesc)
                    End If

                    If CDbl(row(10)) <> 0 Then
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling AddAPInvoice_INTERCO()", sFuncName)
                        If AddAPInvoice_INTERCO(oDIComp(j), row, oDvDtl, sFileName, sErrdesc) <> RTN_SUCCESS Then
                            Throw New ArgumentException(sErrdesc)
                        End If
                    End If

                Next
            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Commit all transaction..........", sFuncName)
            For lCounter As Integer = 0 To UBound(oDIComp)
                If Not oDIComp(lCounter) Is Nothing Then
                    If oDIComp(lCounter).Connected = True Then
                        If oDIComp(lCounter).InTransaction = True Then
                            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Commit transaction on company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                            oDIComp(lCounter).EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                        End If
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                        oDIComp(lCounter).Disconnect()
                        oDIComp(lCounter) = Nothing
                    End If
                End If
            Next


            ProcessARINTERCOFile = RTN_SUCCESS
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion completed successfully.", sFuncName)

        Catch ex As Exception

            For lCounter As Integer = 0 To UBound(oDIComp)
                If Not oDIComp(lCounter) Is Nothing Then
                    If oDIComp(lCounter).Connected = True Then
                        If oDIComp(lCounter).InTransaction = True Then
                            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback transaction on company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                            oDIComp(lCounter).EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                        End If
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                        oDIComp(lCounter).Disconnect()
                        oDIComp(lCounter) = Nothing
                    End If
                End If
            Next

            ProcessARINTERCOFile = RTN_ERROR
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error in Uploading AR File", sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Function

    Private Function AddAPInvoice_INTERCO(ByVal oCompany As SAPbobsCOM.Company, _
                                        ByVal DtRow As DataRow, _
                                        ByVal oDvDtl As DataView, _
                                        ByVal sFileName As String, _
                                        ByRef sErrDesc As String) As Long

        Dim sFuncName As String = "AddAPInvoice_INTERCO"
        Dim sCardCode As String = String.Empty
        Dim oDoc As SAPbobsCOM.Documents
        Dim iCnt As Integer
        Dim lRetCode, lErrCode As Long
        Dim sBatchNo As String = String.Empty
        Dim sBatchPeriod As String = String.Empty
        Dim sRemarks As String = String.Empty

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Creating DI API Object", sFuncName)
            oDoc = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices)

            oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Service

            dtBP.DefaultView.RowFilter = "CardCode = '" & DtRow.Item(18).ToString & "'"
            If dtBP.DefaultView.Count = 0 Then
                sErrDesc = "Cardcode ::" & DtRow.Item(4).ToString & " provided does not exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            dtPURHDr.DefaultView.RowFilter = "U_AI_RefDocNum = '" & DtRow.Item(2).ToString & "'"
            If dtPURHDr.DefaultView.Count <> 0 Then
                sErrDesc = "Document NO ::" & DtRow.Item(2).ToString & " already exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            oDoc.CardCode = DtRow.Item(18).ToString
            oDoc.DocDate = DtRow.Item(3)
            oDoc.DocDueDate = DtRow.Item(3)
            oDoc.TaxDate = DtRow.Item(3)
            oDoc.NumAtCard = DtRow.Item(5).ToString
            oDoc.Comments = DtRow.Item(8).ToString

            oDoc.UserFields.Fields.Item("U_AI_ChitNo").Value = DtRow.Item(6).ToString
            oDoc.UserFields.Fields.Item("U_AI_MARIICCode").Value = DtRow.Item(2).ToString
            oDoc.UserFields.Fields.Item("U_AI_MARIICCompany").Value = DtRow.Item(0).ToString

            oDoc.UserFields.Fields.Item("U_AI_APARUploadName").Value = sFileName


            If CDbl(DtRow.Item(14)) > 0 Then
                oDoc.DocRate = CDbl(DtRow.Item(14))
            End If

            oDoc.UserFields.Fields.Item("U_AI_RefDocNum").Value = DtRow.Item(2).ToString

            Dim DtlRows() As DataRow = oDvDtl.Table.Select("F1='" & DtRow.Item(2).ToString & "'")

            For Each LineRow As DataRow In DtlRows
                iCnt += 1
                If iCnt > 1 Then
                    oDoc.Lines.Add()
                End If

                oDoc.Lines.AccountCode = LineRow(7).ToString
                oDoc.Lines.ItemDescription = LineRow(3).ToString
                oDoc.Lines.LineTotal = CDbl(LineRow(9))


                '* Change 9th October - handle negative GST Amount
                If CDbl(DtRow.Item(11)) > 0 Or CDbl(DtRow.Item(11)) < 0 Then
                    oDoc.Lines.VatGroup = "SI"
                Else
                    oDoc.Lines.VatGroup = "ZI"
                End If

                If Not DtRow(19).ToString = String.Empty Then
                    oDoc.Lines.CostingCode2 = DtRow(19).ToString
                    oDoc.Lines.COGSCostingCode2 = DtRow(19).ToString
                End If

            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding ARI.", sFuncName)
            lRetCode = oDoc.Add
            If lRetCode <> 0 Then
                oCompany.GetLastError(lErrCode, sErrDesc)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding ARI failed.", sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion Completed Succesfully.", sFuncName)
            AddAPInvoice_INTERCO = RTN_SUCCESS

        Catch ex As Exception
            AddAPInvoice_INTERCO = RTN_ERROR
            sErrDesc = ex.Message
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile("Function completed with ERROR:" & sErrDesc, sFuncName)
        End Try

    End Function

End Module
